<?php

namespace App\Service\Activity;

use App\Enums\BaseErrorCode;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Library\Rms\RmsShopApi;
use App\Models\Activity\ActivityActionModel;
use App\Models\Activity\ActivityModel;
use App\Models\Activity\ActivityShopJoinFeedbackModel;
use App\Models\Activity\ActivityShopJoinModel;
use App\Models\Activity\ActivityShopRelModel;
use App\Models\BaseModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseOrderProcessV2Model;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\Shop\ShopModel;
use App\Remote\Orm\OrmNewOrderRemote;
use App\Remote\Orm\ShopRemote;
use App\Service\BaseService;
use App\Service\Cruise\Mission\ActivityInputService;
use App\Service\OpenShop\Feishu\ConfigService;
use App\Service\OpenShop\Feishu\KfosService;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ShopActivityService extends BaseService
{


    // 活动反馈内容对应类型
    const TYPE_FEEDBACK              = 'feedback';      // 活动反馈内容
    const TYPE_FEEDBACK_IMAGES       = 'feedbackImages';// 活动反馈图片
    const TYPE_FEEDBACK_VIDEOS       = 'feedbackVideos';// 活动反馈视频
    const TYPE_FEEDBACK_SHOP_CONTACT = 'shopContact';   // 门店联系方式

    const TYPE_FEEDBACK_MAPPING = [
        self::TYPE_FEEDBACK              => 'string',
        self::TYPE_FEEDBACK_IMAGES       => 'array',
        self::TYPE_FEEDBACK_VIDEOS       => 'array',
        self::TYPE_FEEDBACK_SHOP_CONTACT => 'mobile',
    ];

    const SCREEN_STATUS_OPEN      = 1;
    const SCREEN_STATUS_CAN_CLOSE = 2;
    const SCREEN_STATUS_MAPPING   = [
        self::SCREEN_STATUS_OPEN      => '打开',
        self::SCREEN_STATUS_CAN_CLOSE => '可关闭',
    ];

    const ACTIVITY_TYPE_1 = 1;// 1-消杀活动

    /**
     * 霸屏通用接口
     * @param int $shopId
     * @return array
     */
    public static function getDominatingScreen(int $shopId): array
    {
        $time = time();

        // 活动 - 主表
        $activity = ActivityModel::query()
                                 ->whereIn('status', [ActivityModel::STATUS_1])
                                 ->where(function ($query) {
                                     $query->where("expireType", ActivityModel::EXPIRE_TYPE_0)
                                           ->orWhere(function ($query) {
                                               $query->where("expireType", ActivityModel::EXPIRE_TYPE_1)
                                                     ->where('startTime', '<', time())
                                                     ->where('endTime', '>', time());
                                           });
                                 })
                                 ->where(function ($query) use ($shopId) {
                                     $query->where("shopType", ActivityModel::SHOP_TYPE_ALL)
                                           ->orWhere(function ($query) use ($shopId) {
                                               $query->where("shopType", ActivityModel::SHOP_TYPE_PART)
                                                     ->whereHas("shopRel", function ($query) use ($shopId) {
                                                         $query->where("shopId", $shopId)
                                                               ->where("isDeleted", BaseModel::DELETE_NO);
                                                     });
                                           });
                                 })
//                                 ->whereNotIn("id", function ($query) use ($shopId) {
//                                     $query->select("activityId")->from((new ActivityShopJoinModel())->getTable())
//                                           ->where("shopId", $shopId)
//                                           ->where("status", ActivityShopJoinModel::STATUS_3)
//                                           ->where("isDeleted", BaseModel::DELETE_NO);
//                                 })
                                 ->where('superScreenSwitch', ActivityModel::SWITCH_ON)// 首页霸屏开关 [ 1:开启 0:关闭 ]
                                 ->orderByDesc('id')
                                 ->first();

        if (!$activity) {
            return [];
        }

        // 活动 - 可参与门店关联配置表
        $activityShopRel = ActivityShopRelModel::query()
            ->where('shopId', $shopId)
            ->where('activityId', $activity->id)
            ->first();
        if (!$activityShopRel) {
            return [];
        }

        // 活动 - 门店参与表
        $activityShopJoin = ActivityShopJoinModel::getAppliedStatus($activity->id, $shopId, 0, 0, ActivityShopJoinModel::STATUS_3);
        if ($activityShopJoin) {
            return [];
        }

        $status = 0;
        if ($activity->startTime < $time) {// 活动期间 可根据频次显示 可关闭
            $status = self::SCREEN_STATUS_CAN_CLOSE;// 可关闭
        }
        if ($activity->superScreenStartTime < $time && $activity->superScreenEndTime > $time) {// 霸屏期间 不可关闭
            $status = self::SCREEN_STATUS_OPEN;          // 打开
        }
        $url = config('open-shop.m') . 'activity/v2?id=' . $activity->id;// 前端跳转url
        return [
            'type'        => self::ACTIVITY_TYPE_1,          // 类型 1-消杀活动
            'activityId'  => $activity->id,                  // 活动id
            'status'      => $status,                        // 门店参与活动状态 默认0-不显示霸屏 1-显示霸屏 2-显示霸屏可关闭
            'url'         => $url,                           // 前端跳转url
            'title'       => $activity->popUpTitle ?? '',    // 标题
            'content'     => $activity->popUpContent ?? '',  // 内容
            'frequency'   => $activity->superScreenFrequency,// 弹窗频次 1-不显示 2-仅一次 3-每天一次 4-每次打开APP
            "confirmText" => "查看详情"
        ];
    }


    /**
     * 获取门店活动详情
     *
     * @param int $activityId
     * @param int $shopId
     * @return array
     * @throws GuzzleException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function getActivityInfo(int $activityId, int $shopId): array
    {
        $detail = ActivityModel::query()
                               ->with(['shopActionRel' => function($query){
                                   $query->where("hiddenSwitch", ActivityModel::SWITCH_OFF);
                               }])
                               ->where('id', $activityId)
                               ->first() ?? [];
        if (empty($detail)) {
            return BaseService::returnData(0, '活动不存在');
        }
        $shopModel = ShopModel::query()->where('id', $shopId)->first();

        $openMain = OpenShopMainProcessModel::query()->where('shopId', $shopId)->orderBy('id')->first();

        // 是否已经参与活动
        $appliedStatus  = 0;
        $activityAction = [];

        if ($detail->shopActionRel) {
            $activityAction = $detail->shopActionRel->map(
                function ($item) use ($activityId, $shopId, &$appliedStatus) {
                    $joinInfo         = [];
                    $activityShopJoin = ActivityShopJoinModel::getAppliedStatus($activityId, $shopId, $item->id, $item->actionType);
                    if ($activityShopJoin) {
                        $tempAppliedStatus = $activityShopJoin->status ?? 0;

                        // 参与状态优先级
                        $priorityTemp = ActivityShopJoinModel::STATUS_PRIORITY[$tempAppliedStatus] ?? 99;
                        $priorityNow = ActivityShopJoinModel::STATUS_PRIORITY[$appliedStatus] ?? 99;

                        // 取优先级高的状态
                        if ($priorityTemp < $priorityNow) {
                            $appliedStatus = $tempAppliedStatus;
                        }

                        $joinInfo      = [
                            'id'      => $activityShopJoin->id,
                            'orderId' => $activityShopJoin->orderNo,
                            'uuid'    => $activityShopJoin->uuid,
                            'status'  => $activityShopJoin->status,
                        ];
                    }
                    return [
                        'id'                    => $item->id,                          // 活动选择行为动作id
                        'actionType'            => $item->actionType,                  // 活动行为步骤类型
                        'name'                  => $item->name,                        // 动作名称
                        'remark'                => $item->remark,                      // 备注说明
                        'price'                 => $item->price,                       // 项目参加费用 实付金额
                        'originalPrice'         => $item->originalPrice,               // 项目参加费用 原价
                        'goodsId'               => $item->goodsId,                     // 项目关联订货商品id
                        'goodsName'             => $item->goodsName ?? '',             // 项目商品名称
                        'goodsNum'              => $item->goodsNum,                    // 项目商品数量
                        'shippingAddressSwitch' => $item->shippingAddressSwitch,       // 是否需要配送
                        'shippingAddressType'   => $item->shippingAddressType,         // 配送地址选项类型
                        'formTemplateId'        => $item->formTemplateId,              // 表单模版id
                        'joinInfo'              => $joinInfo,                          // 门店参与记录
                    ];
                }
            );
        }

        $superScreenContent = "";
        if ($detail->superScreenSwitch) {
            if ($detail->superScreenEndTime < time()) {
                $superScreenContent = $detail->superScreenAfterContent;// 霸屏后提示内容
            }
            if ($detail->superScreenEndTime > time()) {
                $superScreenContent = $detail->superScreenBeforeContent;// 霸屏前提示内容
            }
        }


        // 查询是否有已完成的记录
        $getSucInfo = ActivityShopJoinModel::getAppliedStatus($activityId, $shopId, 0, 0, ActivityShopJoinModel::STATUS_3);
        if ($getSucInfo) {
            $appliedStatus = ActivityShopJoinModel::STATUS_3;
        }else{
            // 判断是否有驳回记录
            $rejectExists = ActivityShopJoinModel::getAppliedStatus($activityId, $shopId, 0, 0, ActivityShopJoinModel::STATUS_2);
            if($rejectExists){
                // 最后审核时间
                $auditLast = $rejectExists
                    ->cruiseOrderProcessV2Rel
                    ->where('cruiseOrderStatus', CruiseOrderModel::STATUS_NOT_REVIEW)
                    ->sortByDesc('id')
                    ->first();
                $rejectReason = $auditLast ? ($auditLast['content'] ?? '') : '';
                if($rejectReason){
                    $superScreenContent = $rejectReason;
                }
            }
        }



        return BaseService::returnData(
            1, '', [
                // 详情
                'detail'         => [
                    'id'                    => $detail->id,
                    'name'                  => $detail->name,
                    'expireType'            => $detail->expireType,
                    'expireTypeText'        => ActivityModel::EXPIRE_TYPE_TEXT[$detail->expireType] ?? '-',
                    'startTime'             => $detail->startTime > 0 ? Carbon::createFromTimestamp($detail->startTime)
                        ->format('Y-m-d H:i:s') : '-',
                    'endTime'               => $detail->startTime > 0 ? Carbon::createFromTimestamp($detail->endTime)
                        ->format('Y-m-d H:i:s') : '-',
                    'detail'                => $detail->detail,
                    'shopType'              => $detail->shopType,
                    'shopTypeText'          => ActivityModel::SHOP_TYPE_TEXT[$detail->shopType] ?? '-',
                    'remark'                => $detail->remark,
                    'status'                => $detail->status,
                    'statusText'            => ActivityModel::STATUS_TEXT[$detail->status] ?? '-',
                    'createdAtText'         => $detail->createdAt->format('Y-m-d H:i:s'),
                    'updatedAtText'         => $detail->updatedAt->format('Y-m-d H:i:s'),
                    'superScreenContent'    => $superScreenContent,                                                 // 详情内容上面 霸屏前/后提示内容
                    'feedbackImgSwitch'     => $detail->feedbackImgSwitch,                                          // 回传照片开关 [ 1:开启 0:关闭 ]
//                    'feedbackExampleImages' => json_decode($detail->feedbackExampleImages ?? '', true) ?? [],       // 回传示例照片
                ],
                // 是否已经回传照片信息
                'isFeedback'     => (bool)ActivityShopJoinModel::getAppliedStatus($activityId, $shopId, 0, 0, ActivityShopJoinModel::STATUS_3, ActivityShopJoinModel::FEEDBACK_STATUS_1),
                // 是否是活动门店
                'isShopCanApply' => ActivityShopRelModel::getActivityShopRel($activityId, $shopId),
                // 是否存在订货单
                'isExistOrder'   => in_array($shopId, ShopRemote::hasOrderShopLists()["shop_ids"]),
                // 是否存在订货建党
                'isExistKfos'    => empty($openMain) ? false : (in_array(
                    $openMain->compareStepStatusSort(MissionTemplateEnum::STEP_STATUS_7),
                    ['>', '=']
                )), // 简单处理
                // 是否已经参与完成
                'appliedStatus'  => $appliedStatus,
                // 当前用户是否是督导
                'isNoAuth'       => false,
                // 门店详情
                'shopDetail'     => $shopModel ? $shopModel->only(['id', 'name']) : null,
                'activityAction' => $activityAction,
                'isWhiteShop'    => in_array($shopId, jsonToArr($detail->whiteShopIds, []))
            ]
        );
    }

    /**
     * 活动-创建门店参与记录
     * @param int $shopId
     * @param int $userId
     * @param string $username
     * @param int $activityActionId
     * @return array
     */
    public static function createOrder(int $shopId, int $userId, string $username, int $activityActionId): array
    {
        self::checkUserAuth($shopId, $userId);// 检查用户权限是否可下单/提交表单

        $activityAction = ActivityActionModel::query()
            ->where('id', $activityActionId)
            ->first();

        if (!$activityAction) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '活动动作id不存在');
        }

//        if ($activityAction->actionType == ActivityActionModel::ACTION_TYPE_2) {
//            // 表单类型渠道 有且只能存在一条校验
//            $actionTypeJoinRow = ActivityShopJoinModel::getActionTypeJoinRow(
//                $shopId,
//                $activityAction->activityId,
//                $activityAction->actionType
//            );
//            if ($actionTypeJoinRow && $actionTypeJoinRow->activityActionId != $activityActionId) {
//                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '当前参与渠道表单已创建，请返回刷新查看详情');
//            }
//        }

        // 查询是否有已完成的记录
        $getSucInfo = ActivityShopJoinModel::getAppliedStatus($activityAction->activityId, $shopId, 0, 0, ActivityShopJoinModel::STATUS_3);
        $model      = ActivityShopJoinModel::getAppliedStatus($activityAction->activityId, $shopId, $activityActionId, $activityAction->actionType);
        if (!$model && $getSucInfo) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '活动已参与');
        }
        $data = [
            'activity' => [// 活动信息
                'id'                  => $activityAction->activityId,
                'price'               => $activityAction->price,              // 项目参加费用
                'goodsId'             => $activityAction->goodsId,            // 项目关联订货商品id
                'goodsNum'            => $activityAction->goodsNum,           // 项目商品数量
                'goodsInfo'           => $activityAction->goodsInfo,          // 订货商品信息
                'shippingAddressType' => $activityAction->shippingAddressType,// 配送地址选项类型 [ 1:直配地址 2:订货地址 ]
            ],
        ];
        switch ($activityAction->actionType) {
            case ActivityActionModel::ACTION_TYPE_1:// 支付订单
                if (!$model) {// 没有订单 需要新建

                    $model                   = new ActivityShopJoinModel();
                    $model->shopId           = $shopId;                                  // 门店id
                    $model->activityId       = $activityAction->activityId;              // 活动id
                    $model->activityActionId = $activityActionId;                        // 活动行为表 (activity_action.id)
                    $model->actionType       = $activityAction->actionType;              // 1:支付订单 2:表单填写
                    $model->orderNo          = '';                                       // 关联单号 [ 支付:订货单号 | 表单: cruise_order.id ]
                    $model->status           = 0;                                        // 参与状态 [ 0:已生成 1:待审核 2:已完成 ]
                    $model->submitUseId      = 0;                                        // 提交人uid
                    $model->submitUsername   = '';                                       // 提交人名称
                    $model->uuid             = Str::uuid()->toString();                  // 传给订货唯一id (支付完成更新订货单号)
                    $model->save();
                }
                $data['activityAction'] = [
                    'id'               => $model->id,
                    'activityActionId' => $model->activityActionId,
                    'actionType'       => $model->actionType,
                    'orderNo'          => $model->orderNo,// 订货单号
                    'uuid'             => $model->uuid,
                    'status'           => $model->status,
                    'form'             => [],
                ];
                break;
            case ActivityActionModel::ACTION_TYPE_2:// 表单填写
                if (!$model) {// 没有订单 需要新建

                    if (!$activityAction->formTemplateId) {
                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '活动模版表单id不存在');
                    }
                    DB::beginTransaction();
                    try {
                        $res = ActivityInputService::initOrder($shopId, $userId, $activityAction->formTemplateId);

                        $cruiseOrderId = $res->cruiseOrderModel->id;

                        $model                   = new ActivityShopJoinModel();
                        $model->shopId           = $shopId;                    // 门店id
                        $model->activityId       = $activityAction->activityId;// 活动id
                        $model->activityActionId = $activityActionId;          // 活动行为表 (activity_action.id)
                        $model->actionType       = $activityAction->actionType;// 1:支付订单 2:表单填写
                        $model->orderNo          = $cruiseOrderId;             // 关联单号 [ 支付:订货单号 | 表单: cruise_order.id ]
                        $model->status           = 0;                          // 参与状态 [ 0:已生成 1:待审核 2:已完成 ]
                        $model->submitUseId      = $userId;                    // 提交人uid
                        $model->submitUsername   = $username;                  // 提交人名称
                        $model->save();

                        DB::commit();
                    } catch (Exception $e) {
                        Log::error(
                            'inputsAddErr', [
                                'shopId'           => $shopId,
                                'activityActionId' => $activityActionId,
                                'userId'           => $userId,
                                'msg'              => $e->getMessage(),
                            ]
                        );

                        DB::rollBack();
                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '新建表单失败');
                    }

                } else {
                    $cruiseOrderId = $model->orderNo;
                }

                $data['activityAction'] = [
                    'id'               => $model->id,
                    'activityActionId' => $model->activityActionId,
                    'actionType'       => $model->actionType,
                    'orderNo'          => $model->orderNo,// 表单: cruise_order.id
                    'uuid'             => $model->uuid,
                    'status'           => $model->status,
                    'form'             => (new ActivityInputService($cruiseOrderId, $userId))->getInputObjectFill(),
                ];
                break;
            case ActivityActionModel::ACTION_TYPE_3:// 立即报名
                if (!$model) {// 没有订单 需要新建

                    $model                   = new ActivityShopJoinModel();
                    $model->shopId           = $shopId;                           // 门店id
                    $model->activityId       = $activityAction->activityId;       // 活动id
                    $model->activityActionId = $activityActionId;                 // 活动行为表 (activity_action.id)
                    $model->actionType       = $activityAction->actionType;       // 1:支付订单 2:表单填写
                    $model->orderNo          = '';                                // 关联单号 [ 支付:订货单号 | 表单: cruise_order.id ]
                    $model->status           = ActivityShopJoinModel::STATUS_3;   // 参与状态 [ 0:已生成 1:待审核 2:已完成 ]
                    $model->joinTime         = time();                            // 参与时间
                    $model->submitUseId      = $userId;                           // 提交人uid
                    $model->submitUsername   = $username;                         // 提交人名称
                    $model->save();
                }

                $data['activityAction'] = [
                    'id'               => $model->id,
                    'activityActionId' => $model->activityActionId,
                    'actionType'       => $model->actionType,
                    'orderNo'          => $model->orderNo,// 表单: cruise_order.id
                    'uuid'             => $model->uuid,
                    'status'           => $model->status,
                    'form'             => [],
                ];
                break;
            default:
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '活动类型不存在');
        }
        return $data;

    }


    /**
     * 活动-取消订单
     * @param int $shopId
     * @param int $userId
     * @param string $username
     * @param int $activityActionJoinId
     * @return array
     */
    public static function cancelOrder(int $shopId, int $userId, string $username, int $activityActionJoinId): array
    {
        self::checkUserAuth($shopId, $userId);// 检查用户权限是否可下单/提交表单
        $model = ActivityShopJoinModel::query()
            ->where('shopId', $shopId)
            ->where('id', $activityActionJoinId)
            ->whereIn('status', [ActivityShopJoinModel::STATUS_0, ActivityShopJoinModel::STATUS_1, ActivityShopJoinModel::STATUS_2])
            ->first();
        if (!$model) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '未找到记录');
        }

        switch ($model->actionType) {
            case ActivityActionModel::ACTION_TYPE_1:// 支付订单
                $model->isDeleted = 1;
                $model->save();

                // 取消订货单
                if ($model->orderNo) {
                    $orm = OrmNewOrderRemote::batchCloseOrder([$model->orderNo], $userId, $username, '用户取消订货单');
                    if (!isset($orm['code']) || $orm['code'] != 200) {
                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '关闭订单失败');
                    }
                }
                break;
            case ActivityActionModel::ACTION_TYPE_2:// 表单填写
                $model->isDeleted = 1;
                $model->save();
                break;
            case ActivityActionModel::ACTION_TYPE_3:// 立即报名

                break;
            default:
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '活动类型不存在');
        }
        return [];

    }

    /**
     * 检查用户权限是否可下单/提交表单
     * @param int $shopId
     * @param int $userId
     */
    public static function checkUserAuth(int $shopId, int $userId)
    {

        // 门店信息
//        $shopInfo = ShopModel::query()->where('id', $shopId)->first();

        // 判断门店督导是否是当前用户
//        if ($userId == $shopInfo->councilorId) {
//            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '督导无法参与活动');
//        }

        // 是否能参与
        /*$isCanApply = KfosService::checkHasFirstDeliveryNotes($shopId);
        if (!$isCanApply) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '您还没有发货单，无法参与活动');
        }*/
    }

    /**
     * 获取表单详情没有则创建
     * @param int $shopId
     * @param int $userId
     * @param string $username
     * @param int $activityActionId
     * @return array
     */
    public static function inputsAdd(int $shopId, int $userId, string $username, int $activityActionId): array
    {
        return self::createOrder($shopId, $userId, $username, $activityActionId);
    }


    /**
     * 表单记录详情
     * @param int $shopId
     * @param int $userId
     * @param int $cruiseId
     * @return array
     */
    public static function inputsInfo(int $shopId, int $userId, int $cruiseId): array
    {
        $activityShopJoin = ActivityShopJoinModel::query()
            ->where('shopId', $shopId)
            ->where('orderNo', $cruiseId)
            ->first();

        if (!$activityShopJoin) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '未找到表单记录');
        }

        $data = (new ActivityInputService($activityShopJoin->orderNo, $userId))->getInputObjectFill();
        $data['rejectReason'] = $activityShopJoin
            ->cruiseOrderProcessV2Rel
            ->where('cruiseOrderStatus', CruiseOrderModel::STATUS_NOT_REVIEW)
            ->where('type', CruiseOrderProcessV2Model::TYPE_REJECT)
            ->sortByDesc('id')
            ->first()['content'] ?? '';

        return $data;
    }


    /**
     * 表单记录修改
     * @param int $shopId
     * @param int $userId
     * @param int $cruiseId
     * @param string $field
     * @param $value
     * @param array $auditValue
     * @return array
     */
    public static function inputsUpdate(int $shopId, int $userId, int $cruiseId, string $field, $value, array $auditValue): array
    {
        $activityShopJoin = ActivityShopJoinModel::query()
            ->where('shopId', $shopId)
            ->where('orderNo', $cruiseId)
            ->first();
        if (!$activityShopJoin) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '未找到表单记录');
        }

        $activity = ActivityModel::query()
            ->where('id', $activityShopJoin->activityId)
            ->first();

        if (!$activity) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '活动不存在');
        }

        (new ActivityInputService($activityShopJoin->orderNo, $userId))->saveUserContentJson($field, $value, $auditValue);
        return [];
    }


    /**
     * 表单记录提交
     * @param int $shopId
     * @param int $userId
     * @param int $cruiseId
     * @return array
     */
    public static function inputsSubmit(int $shopId, int $userId, int $cruiseId): array
    {
        $activityShopJoin = ActivityShopJoinModel::query()
            ->where('shopId', $shopId)
            ->where('orderNo', $cruiseId)
            ->first();
        if (!$activityShopJoin) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '未找到表单记录');
        }

        $activity = ActivityModel::query()
            ->where('id', $activityShopJoin->activityId)
            ->first();

        if (!$activity) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '活动不存在');
        }

        (new ActivityInputService($activityShopJoin->orderNo, $userId))->submitOrder();
        return [];
    }


    /**
     * 反馈记录详情
     * @param int $activityId
     * @param int $shopId
     * @param object $user
     * @return array
     */
    public static function getFeedbackDetail(int $activityId, int $shopId, object $user): array
    {
        $activity = ActivityModel::query()->where('id', $activityId)->first();
        if (!$activity) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '活动不存在');
        }

        $info = ActivityShopJoinFeedbackModel::getActivityShopInfo($activityId, $shopId);

        $info['feedbackExampleImages'] = json_decode($activity->feedbackExampleImages ?? '', true) ?? [];       // 回传示例照片
        if (empty($info["shopContact"])){
            $info["shopContact"] = attributeGet($user, "mobile", "");
        }
        return $info;
    }

    /**
     * 反馈记录详情保存
     * @param int $activityId
     * @param int $shopId
     * @param int $userId
     * @param string $username
     * @param array $data
     * @return array
     */
    public static function feedbackSave(int $activityId, int $shopId, int $userId, string $username, array $data): array
    {
        $res = ActivityShopJoinModel::getAppliedStatus($activityId, $shopId, 0, 0, ActivityShopJoinModel::STATUS_3);
        if (!$res) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "未查询到门店参与活动记录");
        }
//        if ($res->feedbackStatus == ActivityShopJoinModel::FEEDBACK_STATUS_1) {
//            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '门店已回传信息');
//        }

        DB::beginTransaction();
        try {
            // 删除历史回传记录信息
            ActivityShopJoinFeedbackModel::query()
                                         ->where("activityId", $activityId)
                                         ->where("shopJoinId", $res->id)
                                         ->update([
                                             "isDeleted"    => BaseModel::DELETE_YES,
                                             "updatedAt"    => time(),
                                             "updatedByUid" => $userId
                                         ]);

            $batchData = [];
            foreach ($data as $k => $v) {
                $type        = self::TYPE_FEEDBACK_MAPPING[$k] ?? 'string';
                $batchData[] = [
                    'activityId' => $activityId,
                    'shopJoinId' => $res->id,
                    'key'        => $k,                                                            // 上传字段key
                    'type'       => $type,                                                         // 值类型
                    'value'      => is_array($v) ? json_encode($v, JSON_UNESCAPED_UNICODE) : $v,   // 上传字段value
                ];
            }

            ActivityShopJoinFeedbackModel::query()->insert($batchData);

            // 修改回传状态
            ActivityShopJoinModel::query()
                ->where('id', $res->id)
                ->update(
                    [
                        'feedbackStatus'   => ActivityShopJoinModel::FEEDBACK_STATUS_1,        // 回传状态
                        'feedbackTime'     => time(),                                          // 回传时间
                        'feedbackUid'      => $userId,                                         // 回传提交用户uid
                        'feedbackUsername' => $username,                                       // 回传提交用户名称
                    ]
                );
            DB::commit();
        } catch (Exception $e) {
            Log::error(
                'feedbackSaveErr', [
                    'activityId' => $activityId,
                    'shopId'     => $shopId,
                    'userId'     => $userId,
                    'data'       => $data,
                    'msg'        => $e->getMessage(),
                ]
            );

            DB::rollBack();
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '回传信息失败');
        }
        return [];
    }

    /**
     * join记录完成后，关闭其他表单和订货单
     * @param int $joinId
     * @return void
     */
    public static function closeOtherAction(int $joinId): void
    {
        $join = ActivityShopJoinModel::query()->find($joinId);
        if (!$join) {
            return;
        }

        ActivityShopJoinModel
            ::query()
            ->with('activityActionRel')
            ->where('activityId', $join->activityId)
            ->where('shopId', $join->shopId)
            ->where('id', '!=', $joinId)
            ->get()
            ->each(function (ActivityShopJoinModel $activityShopJoinModel) {

                $activityShopJoinModel->update(['isDeleted' => 1]);

                if (!$activityShopJoinModel->activityActionRel) {
                    return;
                }

                // 订货单关闭
                if ($activityShopJoinModel->activityActionRel->actionType == ActivityActionModel::ACTION_TYPE_1) {
                    $orm = OrmNewOrderRemote::batchCloseOrder([$activityShopJoinModel->orderNo], 0, '系统', '已参与其他活动类型，取消订货单');
                    /*if (!isset($orm['code']) || $orm['code'] != 200) {
                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '关闭订单失败');
                    }*/
                }

                // 表单关闭
                if ($activityShopJoinModel->activityActionRel->actionType == ActivityActionModel::ACTION_TYPE_2) {

                    CruiseOrderModel::query()
                                    ->where('id', $activityShopJoinModel->orderNo)
                                    ->update(['status' => CruiseOrderModel::STATUS_CLOSED]);
                }
            });

    }

    /**
     * 订单支付完成-更新记录
     * @param int $orderId
     * @param string $code
     * @param string $uuid
     * @param int $payUserid
     * @param string $payUserName
     * @param string $address
     * @param int $payTime
     * @return array
     */
    public static function orderPaymentCompletedAfter(int $orderId, string $code, string $uuid, int $payUserid, string $payUserName, string $address, int $payTime): array
    {
        try {
            $activityShopJoin = ActivityShopJoinModel::query()
                ->where('uuid', $uuid)
                ->where('status', ActivityShopJoinModel::STATUS_0)
                ->first();

            if ($activityShopJoin) {
                ActivityShopJoinModel::query()
                    ->where('id', $activityShopJoin->id)
                    ->update(
                        [
                            'orderNo'        => $orderId,                              // 订货单id
//                            'orderNo'        => $code,                                 // 订货单号
                            'submitUseId'    => $payUserid,                            // 发起支付人uid
                            'submitUsername' => $payUserName,                          // 发起支付人名称
                            'address'        => $address,                              // 支付行为 - 回调的收货地址信息
                            'status'         => ActivityShopJoinModel::STATUS_3,       //  0:已生成 1:待审核 2:已驳回 3:已完成
                            'joinTime'       => $payTime,                              // 支付行为: 支付时间
                        ]
                    );

                self::closeOtherAction($activityShopJoin->id);// join记录完成后，关闭其他表单和订货单
            }
        } catch (Exception $e) {
            Log::info(
                'orderPaymentCompletedAfterErr', [
                    'orderId'     => $orderId,
                    'orderNo'     => $code,
                    'uuid'        => $uuid,
                    'payUserid'   => $payUserid,
                    'payUserName' => $payUserName,
                    'address'     => $address,
                    'payTime'     => $payTime,
                    'msg'         => $e->getMessage(),
                ]
            );
        }
        return [];
    }

    /**
     * 同步活动参与详情数据信息[ 订货订单创建成功调用 ]
     *
     * @param array $data
     * @throws Exception
     */
    public static function syncActivityJoinDetail(array $data)
    {
        try {
            $activityShopJoin = ActivityShopJoinModel::query()
                                                     ->where('uuid', $data["uuid"])
                                                     ->first();

            if ($activityShopJoin && !$activityShopJoin->orderNo) {
                // 更新订单号
                ActivityShopJoinModel::query()
                                     ->where('id', $activityShopJoin->id)
                                     ->update(
                                         [
                                             "orderNo"        => $data["id"], // 订货单id
                                             "submitUsername" => $data["create_username"],
                                             "submitUseId"    => $data["create_uid"],
//                                             "status"         => ActivityModel::STATUS_3,
//                                             "joinTime"       => time()
                                         ]
                                     );
            }
        } catch (Exception $e) {
            logException(
                "nsq - 消杀活动订阅 - 订货订单支付",
                $e,
                $data,
                true,
                true
            );
        }
    }

    /**
     * 同步活动参与收货地址数据信息[ 订货订单收货地址创建成功调用 ]
     *
     * @param array $data
     * @throws Exception
     */
    public static function syncActivityJoinAddressDetail(array $data)
    {
        try{
            $uuid = attributeGet($data, "new_order_uuid", "");
            if (strlen($uuid) > 0) {
                $activityShopJoinModel = ActivityShopJoinModel::query()->where("uuid", $uuid)->first();
                if ($activityShopJoinModel && !$activityShopJoinModel->address) {
                    $address = vsprintf("%s-%s-%s-%s", [
                        attributeGet($data, "province", ""),
                        attributeGet($data, "city", ""),
                        attributeGet($data, "district", ""),
                        attributeGet($data, "detail_address", ""),
                    ]);
                    ActivityShopJoinModel::query()->where("id", $activityShopJoinModel->id)->update([
                        "address"   => $address,
                        "updatedAt" => time()
                    ]);
                }
            }
        }catch (Exception $exception){
            logException(
                "nsq - 消杀活动订阅 - 订货订单收货地址创建成功调用 - 同步活动参与收货地址数据信息",
                $exception,
                $data,
                true,
                true
            );
        }
    }
}
